package lib.persistence.commands;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

import lib.Field;

public class UpdateRow extends CommandAbstract
{

	private Connection conn;

	public UpdateRow() {
		this.conn = global.ConnectionManager.getInstance().getConnection();
	}
	public int execute (int rowId , ArrayList<Field> fields , String tableName) throws SQLException 
	{
		PreparedStatement statement = conn.prepareStatement(getSql(rowId,fields, tableName));
		
		int fieldCount = fields.size();
		for (int i =0; i< fieldCount; i++) 
			setParameter(fields, statement, i);

		int out = statement.executeUpdate();
		
		return out;
	}
	private String getSql(int rowId , ArrayList<Field> fields, String tableName) 
	{
		String cmd = String.format("UPDATE `%s` SET ",tableName);
		int fieldCount = fields.size();
		for (int i =0; i< fieldCount; i++) 
		{
			cmd = cmd.concat(fields.get(i).getName() + " = ? ");
			if (i + 1 < fieldCount)
				cmd = cmd.concat(",");
		}
		cmd = cmd.concat(String.format(" WHERE id = %d ",rowId));
		System.out.println(cmd);
		return cmd;
	}

}
